#include "scripteditor.h"

#include "idocument.h"

#include <QtCore/QEvent>

ScriptEditor::ScriptEditor(QWidget* parent) :QTextEdit(parent), IEditor(),
    m_focusListeners(),
    m_document(),
    m_documentData(0)
{
    installEventFilter(this);
}

ScriptEditor::~ScriptEditor()
{

}

void ScriptEditor::open(const QSharedPointer<IDocument>& document)
{
    m_document = document;

    m_documentData = document->data();

    Q_ASSERT(!m_document.isNull() && m_documentData != 0);

    setDocument(m_documentData);
}

void ScriptEditor::close(const QSharedPointer<IDocument>& document)
{

}

QSharedPointer<IDocument> ScriptEditor::document() const
{
    return m_document;
}

QWidget* ScriptEditor::widget() const
{
    return const_cast<ScriptEditor* >(this);
}

void ScriptEditor::registerFocusListener(QObject* object)
{
    if (!m_focusListeners.contains(object))
    {
        m_focusListeners.append(object);
    }
}

void ScriptEditor::unregisterFocusListener(QObject* object)
{
    if (m_focusListeners.contains(object))
    {
        m_focusListeners.removeAll(object);
    }
}

bool ScriptEditor::eventFilter(QObject* watched, QEvent* event)
{
    bool ret = false;

    if (watched == this && event->type() == QEvent::FocusIn)
    {
        sendFocusEvent();
        ret = true;
    }
    else if (watched == this && event->type() == QEvent::FocusOut)
    {
        sendFocusEvent(false);
        ret = true;
    }

    return ret;
}

void ScriptEditor::sendFocusEvent(bool focusIn) const
{
    /*
    FocusEvent* event = new FocusEvent(focusIn);

    foreach (QObject* listener, m_focusListeners)
    {
        if (!event->isAccepted())
        {
            QApplication::sendEvent(listener, event);
        }
        else
        {
            break;
        }
    }

    delete event;
    */
}
